const url = require('url')
const fs = require('fs')
import Crawler = require('crawler')
import { toDiscipline, slice, resolveBoolean, getRounds, range, getPlayerId, getSeed, getQualification } from './libs/util'
import * as Type from './libs/interfaces'

declare const require: Function

let c1Callback = (err, res): string[] => {
  let { $ } = res
  let $tr = $('#content table.ruler tbody tr')
  let host = `http://www.tournamentsoftware.com/sport/`
  let parsed = slice.call($tr).map(el => {
    let $el = $(el)
    return {
      url: host + $el.find('.drawname a').attr('href'),
      discipline: toDiscipline($el.find('.drawname a').text()),
      size: $el.find('.drawname').next().text(),
      type: $el.find('.drawname').next().next().text(),
      qualification: resolveBoolean($el.find('.drawname').next().next().next().text())
    }
  })
  return parsed.map(el => el.url)
}


let c2Callback = (err, res) => {
  if (err) {
    return console.log(err)
  }
  let { $, body } = res
  let title = $('.title h3').text()
  console.log(title)

  let $tr = $('.draw table tbody tr')
  let trLen = $tr.length
  let participantsLen = (trLen - 1) / 2
  let getByCo = (x, y) => {
    return $($($tr[x]).find('td')[y])
  }
  let getRounds2 = (participantsLen) => {
    let arr = []
    let f = (len) => {
      if (len / 2 > 1) {
        arr.push({ matchesLen: len / 2 })
        f(len / 2)
      }
    }
    f(participantsLen)
    arr.push({ matchesLen: 1 })
    return arr
  }
  let rounds = getRounds2(participantsLen)
  let range2 = (len) => {
    let arr = []
    for (let i = 1; i < len + 1; i++) {
      arr.push(i)
    }
    return arr
  }


  let parsed = rounds.map((round, i) => {
    return range2(round.matchesLen).map(n => {
      let a11 = Math.pow(2, i)
      let a12 = 3 * Math.pow(2, i)

      let team1Td = getByCo(
        a11 + (n - 1) * Math.pow(2, i + 2),
        i + 1
      )

      let team2Td = getByCo(
        a12 + (n - 1) * Math.pow(2, i + 2),
        i + 1
      )

      let scoreTd = getByCo(
        ( Math.pow(2, i + 1) + 1) + ( n - 1 ) * ( 4 * Math.pow(2, i) ),
        i + 2
      )

      let score = slice.call(scoreTd.find('span span')).map(el => {
        let t = $(el).text()
        if (t.indexOf('-') > 0) {
          return t.split('-').map(el => parseInt(el))
        }
        return 'w'
      })

      let teams = [
        {
          players: slice.call(team1Td.find('a:nth-child(2), a:nth-child(5)')).map(el => {
            let $el = $(el)
            return {
              name: $el.text(),
              id: getPlayerId($el.attr('href')),
            }
          }),
          seeded: getSeed(team1Td.find('a:nth-child(2)').text()),
          qualification: getQualification(team1Td.find('a:nth-child(2)').text())
        },
        {
          players: slice.call(team2Td.find('a:nth-child(2), a:nth-child(5)')).map(el => {
            let $el = $(el)
            return {
              name: $el.text(),
              id: getPlayerId($el.attr('href')),
            }
          }),
          seeded: getSeed(team2Td.find('a:nth-child(2)').text()),
          qualification: getQualification(team2Td.find('a:nth-child(2)').text())
        },
      ]


      return {
        teams,
        score
      }
    })
  })

  console.log(parsed)

  fs.writeFile(`json/${title}.json`, JSON.stringify(parsed), () => {})

}


let c = new Crawler({
  rateLimit: 2000,
  maxConnections: 1
})

c.queue({
  uri: 'http://www.tournamentsoftware.com/sport/draws.aspx?id=BB4B9094-EBD8-4769-845C-DBA94B0B790B',
  callback (err, res, done) {
    let urls = c1Callback(err, res)
    let c1 = new Crawler({
      rateLimit: 2000,
      maxConnections: 1,
      callback (err, res, done) {
        c2Callback.apply(this, arguments)
        done()
      }
    })
    c1.queue(urls)
    done()
  }
})
